/// <reference path="../node_modules/autojs-dev/types/auto.d.ts" />

import { StateMachine } from "./core/Fsm";
import { StateNames } from "./consts/StateNames";
import LoadAssertState from "./states/LoadAssertState";
import GameStatusBar from "./GameStatusBar";
import EventBus from "./core/EventBus";
import { EventNames } from "./consts/EventNames";
import GamingState from "./states/GamingState";
import ScreenManager from "./core/ScreenManager";

declare global {

}


class App {
    public fsm: StateMachine;
    public isFreezing: boolean;

    private updateTimerId: number;

    constructor() {
        this.isFreezing = false;
        // this.updateTimerId = setInterval(() => this.onUpdate(), 500);
        setTimeout(() => this.onUpdate(), 10);

        EventBus.on(EventNames.ROLE_FREEZING, (isFreezing: boolean) => {
            this.isFreezing = isFreezing;
        });

        EventBus.on(EventNames.START, () => {
            this.fsm.setState(StateNames.GAMEING);
        });

        EventBus.on(EventNames.LOAD_ASSETS_COMPLETE, () => {
            // EventBus.emit(EventNames.SHOW_MENU_DIALOG);
            this.fsm.setState(StateNames.GAMEING);
        });
    }

    private onUpdate() {
        ScreenManager.captureScreen();
        this.fsm.onUpdate();
        ScreenManager.screenshot.recycle();

        let deltaTime = new Date().getTime() - ScreenManager.lastScreenshotTime;
        setTimeout(() => this.onUpdate(), Math.max(0, 500 - deltaTime));
    }

    private onExit() {
        this.updateTimerId && clearInterval(this.updateTimerId);
        this.fsm.onExit();
    }

    static startup() {
        sleep(1000);
        images.requestScreenCapture(false);
        let app = new App();
        let statusBar = new GameStatusBar();

        const description = {
            [StateMachine.STARTING_STATE]: StateNames.LOAD_ASSETS,
            [StateMachine.STATES]: {
                [StateNames.LOAD_ASSETS]: new LoadAssertState(),
                [StateNames.GAMEING]: new GamingState(),
            }
        }

        app.fsm = new StateMachine(description);

        events.on('exit', () => {
            toast('脚本结束');
            app.onExit();
            statusBar.onExit();
        });
    }
}

App.startup();


